import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, Typography, message, Spin } from 'antd';
import {
  UserOutlined, LockOutlined, EyeOutlined,
  EyeInvisibleOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { loginSync } from "../../store/modules/login";
import './index.css';

const { Title, Text } = Typography;

const Login = () => {
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const dispatch = useDispatch();

  // 确保元素显示的安全机制 - 无论动画如何都显示元素
  useEffect(() => {
    // 确保表单元素显示的双重保险
    const ensureElementsVisible = () => {
      const elements = [
        ...document.querySelectorAll('.form-item'),
        document.querySelector('.login-button')
      ];
      
      elements.forEach(el => {
        if (el) {
          // 强制显示元素
          el.style.opacity = '1';
          el.style.transform = 'translateY(0)';
          // 添加动画类
          el.classList.add('show');
        }
      });
    };

    // 立即执行一次确保显示
    ensureElementsVisible();
    
    // 短暂延迟后再执行一次，防止其他样式干扰
    const timer = setTimeout(ensureElementsVisible, 500);
    
    return () => clearTimeout(timer);
  }, []);

  // 切换密码可见性
  const togglePassword = () => {
    setShowPassword(!showPassword);
  };

  // 处理登录逻辑
  const handleLogin = async (values) => {
    if (!values.account.trim() || !values.password.trim()) {
      message.error('账号和密码不能为空');
      return;
    }

    setLoading(true);
    try {
      const res = await dispatch(loginSync({
        account: values.account.trim(),
        password: values.password.trim()
      }));

      if (res.code === 0) {
        sessionStorage.setItem('token', res.data?.token || '');
        message.success('登录成功！正在进入系统...');

        setTimeout(() => {
          navigate('/');
        }, 500);
      }
    } catch (error) {
      console.error('登录请求失败:', error);
      message.error('网络异常，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-page">
      <div className="bg-pattern"></div>
      <div className="decor-circle top"></div>
      <div className="decor-circle bottom"></div>
      
      <div className="container">
        <div className="brand-section">
          <div className="logo">
            <div className="logo-inner">
              <i className="fa fa-leaf text-white text-3xl"></i>
            </div>
          </div>
          <Title level={2} className="brand-name">
            本草轩理疗坊
          </Title>
          <Text className="brand-slogan">
            传统理疗 · 健康养生
          </Text>
        </div>
        
        <Card className="login-card" variant="outlined" style={{overflow: 'visible'}}>
          
          <Form
            form={form}
            layout="vertical"
            onFinish={handleLogin}
            initialValues={{ remember: true }}
            className="login-form"
          >
            <Form.Item
              name="account"
              rules={[
                { required: true, message: '请输入账号' },
                { min: 4, message: '账号长度不能少于4个字符' }
              ]}
              className="form-item"
              style={{opacity: 1, transform: 'translateY(0)'}}
            >
              <Input
                prefix={<UserOutlined className="input-icon" />}
                placeholder="请输入账号"
                size="large"
                className="login-input"
                style={{opacity: 1}}
              />
            </Form.Item>
            
            {/* 密码输入框 - 强制显示样式 */}
            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码长度不能少于6个字符' }
              ]}
              className="form-item"
              style={{opacity: 1, transform: 'translateY(0)'}}
            >
              <Input
                prefix={<LockOutlined className="input-icon" />}
                type={showPassword ? 'text' : 'password'}
                placeholder="请输入密码"
                size="large"
                className="login-input"
                style={{opacity: 1}}
                suffix={
                  showPassword ? (
                    <EyeOutlined 
                      onClick={togglePassword} 
                      className="toggle-icon"
                    />
                  ) : (
                    <EyeInvisibleOutlined 
                      onClick={togglePassword} 
                      className="toggle-icon"
                    />
                  )
                }
              />
            </Form.Item>
            
            {/* 登录按钮 - 强制显示样式 */}
            <Form.Item className="form-item" style={{opacity: 1, transform: 'translateY(0)'}}>
              <Button
                type="primary"
                htmlType="submit"
                size="large"
                loading={loading}
                className="login-button"
                block
                style={{opacity: 1}}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
      
      <Spin spinning={loading} fullscreen tip="登录中..." />
    </div>
  );
};

export default Login;
